<template>
  <PageContainer title="财务管理">
    <!-- 搜索筛选区域 -->
    <SearchForm v-model="searchForm" @search="handleSearch" @reset="handleReset">
      <el-form-item label="记录筛选">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入用户名或交易单号"
          clearable
        />
      </el-form-item>
      <el-form-item label="交易类型">
        <el-select
          v-model="searchForm.type"
          placeholder="请选择交易类型"
          clearable
        >
          <el-option label="投递收益" value="disposal_income" />
          <el-option label="提现" value="withdrawal" />
          <el-option label="充值" value="recharge" />
          <el-option label="退款" value="refund" />
          <el-option label="扣款" value="deduction" />
          <el-option label="奖励" value="reward" />
        </el-select>
      </el-form-item>
      <el-form-item label="交易状态">
        <el-select
          v-model="searchForm.status"
          placeholder="请选择交易状态"
          clearable
        >
          <el-option label="成功" value="success" />
          <el-option label="处理中" value="processing" />
          <el-option label="失败" value="failed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>
      </el-form-item>
      <el-form-item label="金额范围">
        <div class="amount-range">
          <el-input-number
            v-model="searchForm.minAmount"
            :min="0"
            :max="10000"
            :precision="2"
            placeholder="最小金额"
            style="width: 120px"
          />
          <span style="margin: 0 8px">-</span>
          <el-input-number
            v-model="searchForm.maxAmount"
            :min="0"
            :max="10000"
            :precision="2"
            placeholder="最大金额"
            style="width: 120px"
          />
          <span style="margin-left: 8px; color: #909399">元</span>
        </div>
      </el-form-item>
      <el-form-item label="交易时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
    </SearchForm>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <StatCard
        :icon="Money"
        icon-bg="#67C23A"
        :value="`¥${financeStats.totalIncome}`"
        label="总收入"
        :trend="financeStats.incomeTrend"
      />
      <StatCard
        :icon="CreditCard"
        icon-bg="#E6A23C"
        :value="`¥${financeStats.totalWithdrawal}`"
        label="总提现"
        :trend="financeStats.withdrawalTrend"
      />
      <StatCard
        :icon="Wallet"
        icon-bg="#409EFF"
        :value="`¥${financeStats.totalBalance}`"
        label="平台余额"
        :trend="financeStats.balanceTrend"
      />
      <StatCard
        :icon="DocumentCopy"
        icon-bg="#909399"
        :value="financeStats.totalTransactions"
        label="交易笔数"
        :trend="financeStats.transactionsTrend"
      />
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button
          type="primary"
          @click="handleManualTransaction"
        >
          <el-icon><Plus /></el-icon>
          手动记账
        </el-button>
        <el-button
          type="success"
          @click="handleBatchWithdrawal"
        >
          <el-icon><CreditCard /></el-icon>
          批量提现
        </el-button>
        <el-button
          type="warning"
          :disabled="!selectedRows.length"
          @click="handleBatchRefund"
        >
          <el-icon><RefreshLeft /></el-icon>
          批量退款
        </el-button>
        <el-button
          type="info"
          @click="handleExport"
        >
          <el-icon><Download /></el-icon>
          导出账单
        </el-button>
        <el-button
          type="primary"
          @click="handleStatistics"
        >
          <el-icon><DataAnalysis /></el-icon>
          财务报表
        </el-button>
      </div>
      <div class="action-right">
        <el-button
          type="info"
          @click="loadFinanceList"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 财务记录表格 -->
    <DataTable
      :data="financeList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="记录ID" width="100" />
      <el-table-column prop="transactionNo" label="交易单号" width="180" />
      <el-table-column label="用户信息" width="150">
        <template #default="{ row }">
          <div class="user-info">
            <div class="user-name">{{ row.userName }}</div>
            <div class="user-phone">{{ row.userPhone }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="交易类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getTypeTag(row.type)">
            {{ getTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="交易金额" width="120" sortable>
        <template #default="{ row }">
          <span :class="getAmountClass(row.type)">
            {{ getAmountPrefix(row.type) }}¥{{ row.amount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="账户余额" width="120">
        <template #default="{ row }">
          <span class="balance-amount">¥{{ row.balance }}</span>
        </template>
      </el-table-column>
      <el-table-column label="交易状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" width="120">
        <template #default="{ row }">
          <div v-if="row.paymentMethod" class="payment-method">
            <el-icon>
              <component :is="getPaymentIcon(row.paymentMethod)" />
            </el-icon>
            <span>{{ getPaymentText(row.paymentMethod) }}</span>
          </div>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>
      <el-table-column label="关联订单" width="150">
        <template #default="{ row }">
          <el-link
            v-if="row.relatedOrderNo"
            type="primary"
            @click="handleViewOrder(row.relatedOrderNo)"
          >
            {{ row.relatedOrderNo }}
          </el-link>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>
      <el-table-column label="交易时间" width="180" sortable>
        <template #default="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="处理时间" width="180">
        <template #default="{ row }">
          {{ row.processedAt ? formatDateTime(row.processedAt) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleViewDetail(row)"
          >
            详情
          </el-button>
          <el-button
            v-if="row.status === 'processing'"
            type="success"
            size="small"
            @click="handleConfirm(row)"
          >
            确认
          </el-button>
          <el-dropdown @command="(command: string) => handleMoreAction(command, row)">
            <el-button type="text" size="small">
              更多<el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="view-receipt">查看凭证</el-dropdown-item>
                <el-dropdown-item command="user-profile">用户档案</el-dropdown-item>
                <el-dropdown-item command="transaction-history">交易历史</el-dropdown-item>
                <el-dropdown-item 
                  command="refund" 
                  :disabled="row.status !== 'success' || row.type === 'withdrawal'"
                  divided
                >
                  申请退款
                </el-dropdown-item>
                <el-dropdown-item 
                  command="cancel" 
                  :disabled="row.status !== 'processing'"
                >
                  取消交易
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 交易详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="交易详情"
      width="70%"
    >
      <div v-if="currentTransaction" class="transaction-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-descriptions title="基本信息" :column="1" border>
              <el-descriptions-item label="记录ID">
                {{ currentTransaction.id }}
              </el-descriptions-item>
              <el-descriptions-item label="交易单号">
                {{ currentTransaction.transactionNo }}
              </el-descriptions-item>
              <el-descriptions-item label="用户姓名">
                {{ currentTransaction.userName }}
              </el-descriptions-item>
              <el-descriptions-item label="用户手机">
                {{ currentTransaction.userPhone }}
              </el-descriptions-item>
              <el-descriptions-item label="交易类型">
                <el-tag :type="getTypeTag(currentTransaction.type)">
                  {{ getTypeText(currentTransaction.type) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="交易金额">
                <span :class="getAmountClass(currentTransaction.type)">
                  {{ getAmountPrefix(currentTransaction.type) }}¥{{ currentTransaction.amount }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="账户余额">
                ¥{{ currentTransaction.balance }}
              </el-descriptions-item>
              <el-descriptions-item label="交易状态">
                <el-tag :type="getStatusTag(currentTransaction.status)">
                  {{ getStatusText(currentTransaction.status) }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
          <el-col :span="12">
            <el-descriptions title="交易信息" :column="1" border>
              <el-descriptions-item label="支付方式">
                <div v-if="currentTransaction.paymentMethod" class="payment-method">
                  <el-icon>
                    <component :is="getPaymentIcon(currentTransaction.paymentMethod)" />
                  </el-icon>
                  <span>{{ getPaymentText(currentTransaction.paymentMethod) }}</span>
                </div>
                <span v-else>-</span>
              </el-descriptions-item>
              <el-descriptions-item label="第三方单号">
                {{ currentTransaction.thirdPartyNo || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="关联订单">
                <el-link
                  v-if="currentTransaction.relatedOrderNo"
                  type="primary"
                  @click="handleViewOrder(currentTransaction.relatedOrderNo)"
                >
                  {{ currentTransaction.relatedOrderNo }}
                </el-link>
                <span v-else>-</span>
              </el-descriptions-item>
              <el-descriptions-item label="交易时间">
                {{ formatDateTime(currentTransaction.createdAt) }}
              </el-descriptions-item>
              <el-descriptions-item label="处理时间">
                {{ currentTransaction.processedAt ? formatDateTime(currentTransaction.processedAt) : '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="处理人员">
                {{ currentTransaction.processedBy || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="交易备注">
                {{ currentTransaction.remark || '-' }}
              </el-descriptions-item>
              <el-descriptions-item label="IP地址">
                {{ currentTransaction.ipAddress || '-' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>

        <!-- 交易凭证 -->
        <div v-if="currentTransaction.receipt" class="transaction-receipt" style="margin-top: 20px;">
          <h4>交易凭证</h4>
          <el-image
            :src="currentTransaction.receipt.url"
            :alt="currentTransaction.receipt.description"
            fit="contain"
            style="max-width: 400px; max-height: 300px;"
            :preview-src-list="[currentTransaction.receipt.url]"
          />
          <div class="receipt-info">
            <div>凭证类型：{{ currentTransaction.receipt.type }}</div>
            <div>上传时间：{{ formatDateTime(currentTransaction.receipt.createdAt) }}</div>
          </div>
        </div>

        <!-- 交易流水 -->
        <div class="transaction-flow" style="margin-top: 20px;">
          <h4>交易流水</h4>
          <el-timeline>
            <el-timeline-item
              v-for="(flow, index) in currentTransaction.transactionFlow"
              :key="index"
              :timestamp="formatDateTime(flow.createdAt)"
              :type="getFlowType(flow.action)"
            >
              <div class="flow-content">
                <div class="flow-action">{{ flow.actionText }}</div>
                <div class="flow-operator">操作人：{{ flow.operator }}</div>
                <div v-if="flow.remark" class="flow-remark">备注：{{ flow.remark }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>

    <!-- 手动记账对话框 -->
    <el-dialog
      v-model="manualDialogVisible"
      title="手动记账"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="manualFormRef"
        :model="manualForm"
        :rules="manualRules"
        label-width="100px"
      >
        <el-form-item label="用户选择" prop="userId">
          <el-select
            v-model="manualForm.userId"
            placeholder="请选择用户"
            filterable
            remote
            :remote-method="searchUsers"
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="`${user.name} (${user.phone})`"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="交易类型" prop="type">
          <el-select
            v-model="manualForm.type"
            placeholder="请选择交易类型"
          >
            <el-option label="充值" value="recharge" />
            <el-option label="扣款" value="deduction" />
            <el-option label="奖励" value="reward" />
            <el-option label="退款" value="refund" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易金额" prop="amount">
          <el-input-number
            v-model="manualForm.amount"
            :min="0.01"
            :max="10000"
            :precision="2"
            placeholder="请输入交易金额"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="交易备注" prop="remark">
          <el-input
            v-model="manualForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入交易备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="manualDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleManualSubmit" :loading="submitting">
          确认记账
        </el-button>
      </template>
    </el-dialog>

    <!-- 财务报表对话框 -->
    <el-dialog
      v-model="statisticsDialogVisible"
      title="财务报表"
      width="90%"
    >
      <div class="statistics-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card title="收入趋势">
              <div ref="incomeChart" style="height: 300px;"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card title="支出分析">
              <div ref="expenseChart" style="height: 300px;"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-card title="交易类型分布">
              <div ref="typeChart" style="height: 300px;"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card title="用户消费排行">
              <div ref="userRankChart" style="height: 300px;"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import {
  Money,
  CreditCard,
  Wallet,
  DocumentCopy,
  Plus,
  RefreshLeft,
  Download,
  DataAnalysis,
  Refresh,
  ArrowDown
} from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import SearchForm from '@/components/SearchForm.vue'
import DataTable from '@/components/DataTable.vue'
import StatCard from '@/components/StatCard.vue'
import { useFinanceStore } from '@/stores/finance'
import { formatDateTime } from '@/utils'

const financeStore = useFinanceStore()

const loading = ref(false)
const submitting = ref(false)
const detailDialogVisible = ref(false)
const manualDialogVisible = ref(false)
const statisticsDialogVisible = ref(false)
const currentTransaction = ref<any>(null)
const selectedRows = ref<any[]>([])
const manualFormRef = ref<FormInstance>()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: '',
  status: '',
  minAmount: null,
  maxAmount: null,
  dateRange: []
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 财务统计
const financeStats = reactive({
  totalIncome: '156,890.50',
  incomeTrend: '+18.5%',
  totalWithdrawal: '89,560.20',
  withdrawalTrend: '+12.3%',
  totalBalance: '67,330.30',
  balanceTrend: '+25.8%',
  totalTransactions: '3,256',
  transactionsTrend: '+15.2%'
})

// 财务记录列表
const financeList = ref<any[]>([])

// 用户选项
const userOptions = ref<any[]>([])

// 手动记账表单
const manualForm = reactive({
  userId: '',
  type: 'recharge',
  amount: 0,
  remark: ''
})

// 表单验证规则
const manualRules: FormRules = {
  userId: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择交易类型', trigger: 'change' }
  ],
  amount: [
    { required: true, message: '请输入交易金额', trigger: 'blur' },
    { type: 'number', min: 0.01, max: 10000, message: '金额范围在 0.01 到 10000 元', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入交易备注', trigger: 'blur' },
    { min: 5, max: 200, message: '备注长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取交易类型标签
const getTypeTag = (type: string) => {
  switch (type) {
    case 'disposal_income':
      return 'success'
    case 'withdrawal':
      return 'warning'
    case 'recharge':
      return 'primary'
    case 'refund':
      return 'info'
    case 'deduction':
      return 'danger'
    case 'reward':
      return 'success'
    default:
      return 'info'
  }
}

// 获取交易类型文本
const getTypeText = (type: string) => {
  switch (type) {
    case 'disposal_income':
      return '投递收益'
    case 'withdrawal':
      return '提现'
    case 'recharge':
      return '充值'
    case 'refund':
      return '退款'
    case 'deduction':
      return '扣款'
    case 'reward':
      return '奖励'
    default:
      return '未知类型'
  }
}

// 获取状态标签
const getStatusTag = (status: string) => {
  switch (status) {
    case 'success':
      return 'success'
    case 'processing':
      return 'warning'
    case 'failed':
      return 'danger'
    case 'cancelled':
      return 'info'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'success':
      return '成功'
    case 'processing':
      return '处理中'
    case 'failed':
      return '失败'
    case 'cancelled':
      return '已取消'
    default:
      return '未知状态'
  }
}

// 获取金额样式类
const getAmountClass = (type: string) => {
  switch (type) {
    case 'disposal_income':
    case 'recharge':
    case 'reward':
      return 'income-amount'
    case 'withdrawal':
    case 'deduction':
    case 'refund':
      return 'expense-amount'
    default:
      return 'normal-amount'
  }
}

// 获取金额前缀
const getAmountPrefix = (type: string) => {
  switch (type) {
    case 'disposal_income':
    case 'recharge':
    case 'reward':
      return '+'
    case 'withdrawal':
    case 'deduction':
    case 'refund':
      return '-'
    default:
      return ''
  }
}

// 获取支付方式图标
const getPaymentIcon = (method: string) => {
  switch (method) {
    case 'wechat':
      return 'ChatDotRound'
    case 'alipay':
      return 'Money'
    case 'bank':
      return 'CreditCard'
    default:
      return 'Wallet'
  }
}

// 获取支付方式文本
const getPaymentText = (method: string) => {
  switch (method) {
    case 'wechat':
      return '微信支付'
    case 'alipay':
      return '支付宝'
    case 'bank':
      return '银行卡'
    default:
      return '其他'
  }
}

// 获取流水类型
const getFlowType = (action: string) => {
  switch (action) {
    case 'create':
      return 'primary'
    case 'process':
      return 'success'
    case 'fail':
      return 'danger'
    case 'cancel':
      return 'info'
    default:
      return 'primary'
  }
}

// 加载财务记录列表
const loadFinanceList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    const response = await financeStore.fetchFinanceList(params)
    financeList.value = response.list
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('加载财务记录失败')
  } finally {
    loading.value = false
  }
}

// 搜索用户
const searchUsers = async (query: string) => {
  if (query) {
    // 模拟搜索用户
    userOptions.value = [
      { id: 1, name: '张三', phone: '13800138001' },
      { id: 2, name: '李四', phone: '13800138002' },
      { id: 3, name: '王五', phone: '13800138003' }
    ].filter(user => 
      user.name.includes(query) || user.phone.includes(query)
    )
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadFinanceList()
}

// 重置处理
const handleReset = () => {
  pagination.page = 1
  loadFinanceList()
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.page = page
  loadFinanceList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadFinanceList()
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 查看详情
const handleViewDetail = async (row: any) => {
  // 模拟获取交易详细信息
  currentTransaction.value = {
    ...row,
    thirdPartyNo: 'WX20240115143000001',
    processedBy: '管理员',
    ipAddress: '192.168.1.100',
    receipt: {
      url: 'https://via.placeholder.com/400x300?text=交易凭证',
      type: '支付截图',
      description: '用户提供的支付凭证',
      createdAt: '2024-01-15 14:30:00'
    },
    transactionFlow: [
      {
        action: 'create',
        actionText: '创建交易',
        operator: '系统',
        createdAt: '2024-01-15 14:30:00',
        remark: '用户发起提现申请'
      },
      {
        action: 'process',
        actionText: '处理交易',
        operator: '管理员',
        createdAt: '2024-01-15 14:35:00',
        remark: '审核通过，开始处理'
      },
      {
        action: 'complete',
        actionText: '交易完成',
        operator: '系统',
        createdAt: '2024-01-15 14:40:00',
        remark: '交易处理完成'
      }
    ]
  }
  detailDialogVisible.value = true
}

// 确认交易
const handleConfirm = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      '确定要确认这笔交易吗？',
      '确认交易',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用确认交易API
    ElMessage.success('交易确认成功')
    loadFinanceList()
  } catch (error) {
    // 用户取消
  }
}

// 手动记账
const handleManualTransaction = () => {
  Object.assign(manualForm, {
    userId: '',
    type: 'recharge',
    amount: 0,
    remark: ''
  })
  manualDialogVisible.value = true
}

// 手动记账提交
const handleManualSubmit = async () => {
  if (!manualFormRef.value) return
  
  try {
    await manualFormRef.value.validate()
    submitting.value = true
    
    // 调用手动记账API
    ElMessage.success('记账成功')
    manualDialogVisible.value = false
    loadFinanceList()
  } catch (error) {
    ElMessage.error('记账失败')
  } finally {
    submitting.value = false
  }
}

// 批量提现
const handleBatchWithdrawal = () => {
  ElMessage.info('批量提现功能开发中...')
}

// 批量退款
const handleBatchRefund = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要对选中的 ${selectedRows.value.length} 笔交易进行退款吗？`,
      '批量退款',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用批量退款API
    ElMessage.success('批量退款成功')
    loadFinanceList()
  } catch (error) {
    // 用户取消
  }
}

// 导出账单
const handleExport = () => {
  ElMessage.info('导出账单功能开发中...')
}

// 财务报表
const handleStatistics = () => {
  statisticsDialogVisible.value = true
  nextTick(() => {
    // 这里可以初始化图表
    ElMessage.info('财务报表功能开发中...')
  })
}

// 查看订单
const handleViewOrder = (orderNo: string) => {
  ElMessage.info(`查看订单 ${orderNo} 功能开发中...`)
}

// 更多操作
const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'view-receipt':
      ElMessage.info('查看凭证功能开发中...')
      break
    case 'user-profile':
      ElMessage.info('用户档案功能开发中...')
      break
    case 'transaction-history':
      ElMessage.info('交易历史功能开发中...')
      break
    case 'refund':
      ElMessage.info('申请退款功能开发中...')
      break
    case 'cancel':
      ElMessage.info('取消交易功能开发中...')
      break
  }
}

onMounted(() => {
  loadFinanceList()
})
</script>

<style lang="scss" scoped>
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .action-left,
  .action-right {
    display: flex;
    gap: 12px;
  }
}

.amount-range {
  display: flex;
  align-items: center;
}

.user-info {
  .user-name {
    font-weight: 600;
    margin-bottom: 4px;
  }

  .user-phone {
    font-size: 12px;
    color: #909399;
  }
}

.income-amount {
  color: #67C23A;
  font-weight: 600;
}

.expense-amount {
  color: #F56C6C;
  font-weight: 600;
}

.normal-amount {
  color: #303133;
  font-weight: 600;
}

.balance-amount {
  color: #409EFF;
  font-weight: 600;
}

.payment-method {
  display: flex;
  align-items: center;
  gap: 4px;
}

.text-muted {
  color: #909399;
}

.transaction-detail {
  .transaction-receipt {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }

    .receipt-info {
      margin-top: 12px;
      font-size: 12px;
      color: #909399;

      > div {
        margin-bottom: 4px;
      }
    }
  }

  .transaction-flow {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }

    .flow-content {
      .flow-action {
        font-weight: 600;
        margin-bottom: 4px;
      }

      .flow-operator {
        font-size: 12px;
        color: #909399;
        margin-bottom: 4px;
      }

      .flow-remark {
        font-size: 12px;
        color: #606266;
      }
    }
  }
}

.statistics-content {
  .el-card {
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left,
    .action-right {
      justify-content: center;
    }
  }

  .amount-range {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}
</style>